<template>
  <div class="wen-box">
    <div class="fabu">
      <div class="wenzhangk">
        <span>文章标题</span>
        <el-input placeholder="请输入（模糊查询）" v-model="input" clearable>
        </el-input>
      </div>
      <div class="block">
        <span class="demonstration">发布日期</span>
        <el-date-picker
          v-model="value2"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </div>
      <el-button @click="chaxun" type="primary"
        ><i class="el-icon-search"></i>查询</el-button
      >
      <el-button @click="chognzhi"
        ><i class="el-icon-refresh-left"></i>重置</el-button
      >
    </div>
    <div class="xiewen">
      <el-button @click="xiewen" type="primary"
        ><i class="el-icon-search"></i>写文章</el-button
      >
    </div>
    <div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="标题" width="380">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column label="预览图" width="280">
          <template slot-scope="scope">
            <img
              :src="scope.row.titleImage"
              alt=""
              style="height: 80px; width: 80px"
            />
          </template>
        </el-table-column>
        <el-table-column label="发布时间" width="220">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              @click="handlePreview(scope.$index, scope.row)"
              >预览</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <span class="demonstration"></span>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="from.current"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="from.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      value2: "",
      input: "",
      tableData: [],
      total: 0,
      from: {
        current: 1,
        size: 10,
        searchTitle: null,
        startDate: "",
        endDate: null,
      },
      token: null,
      // records: [],
    };
  },
  created() {
    this.current = 1;
    this.getgot();
  },
  methods: {
    xiewen() {
      this.$router.push("/xiewen");
    },
    chognzhi() {
      this.value2 = "";
      this.input = "";
      this.from.current = 1;
      this.from.size = 10;
      this.getgot();
    },
    chaxun() {
      this.from.current = 1;
      this.getgot();
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.from.size = val;
      this.getgot();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.from.current = val;
      this.getgot();
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.$router.push({
        path: "/wenbiaoji",
        query: { articleId: row.id },
      });
    },
    handlePreview(index, row) {
      console.log(index, row);
      this.$router.replace({
        path: "/home/shouxiang",
        query: { articleId: row.id },
      });
    },
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getdel(row.id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async getdel(articleId) {
      try {
        let res = await this.$axios.post("/admin/article/delete", {
          articleId: articleId,
        });
        if (res.data.success) {
          // 假设接口返回success标识成功
          this.$message.success("删除成功");
          this.getgot(); // 重新加载列表
        }
      } catch (error) {
        this.$message.error("删除失败");
      }
    },
    async getgot() {
      let res = await this.$axios.post("/admin/article/list", {
        current: this.from.current,
        size: this.from.size,
        searchTitle: this.input,
        startTime:
          this.value2 && this.value2.length === 2
            ? this.formatDate(this.value2[0])
            : null,
        endTime:
          this.value2 && this.value2.length === 2
            ? this.formatDate(this.value2[1])
            : null,
      });
      console.log(res);
      if (res.data.errorCode != 10000) {
        this.tableData = res.data.data.records;
        this.total = res.data.data.total;
      }
    },
    formatDate(date) {
      if (!date) return null;
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      // 补充时间（开始日期加 00:00:00，结束日期加 23:59:59，更符合实际筛选需求）
      return `${year}-${month}-${day} ${
        date === this.value2[0] ? "00:00:00" : "23:59:59"
      }`;
    },
  },
};
</script>

<style>
.wen-box {
  margin-top: 4.375rem;
}
.el-table {
  line-height: 2.875rem;
}
.fabu {
  line-height: 2.8125rem;
  text-align: left;
  background-color: #fff;
  margin: 1.25rem auto;
  padding: 1.25rem;
  display: flex;
  justify-content: flex-start;
  gap: 1rem;
}
.demonstration {
  margin-right: 1.25rem;
}
.wenzhangk {
  display: flex;
}
.wenzhangk span {
  width: 6.5rem;
}
.el-icon-search {
  margin-right: 0.625rem;
}
.el-icon-refresh-left {
  margin-right: 0.625rem;
}
.xiewen {
  line-height: 2.5rem;
  background-color: #fff;
  text-align: left;
  padding: 1.25rem;
  /* width: 12.5rem;
  height: 12.5rem; */
}
.block{
  /* width: 25rem; */
}
</style>